package com.wx.springboot.step6.service.impl;

import com.github.pagehelper.PageHelper;
import com.wx.springboot.step6.dto.PageDto;
import com.wx.springboot.step6.exception.ApiAssert;
import com.wx.springboot.step6.exception.ApiException;
import com.wx.springboot.step6.mbg.mapper.BrandMapper;
import com.wx.springboot.step6.mbg.model.Brand;
import com.wx.springboot.step6.mbg.model.BrandExample;
import com.wx.springboot.step6.service.BrandService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class BrandServiceImpl implements BrandService {
    @Autowired
    private BrandMapper brandMapper;

    @Override
    public List<Brand> list() {
        BrandExample example = new BrandExample();
//        example.setOrderByClause(" product_count asc ");
//        BrandExample.Criteria criteria = example.createCriteria();
//        criteria.andNameLike("%小米%");
//        criteria.andProductCountLessThan(100);
//        criteria.andSortEqualTo(200);
        List<Brand> list = brandMapper.selectByExample(example);
        return list;
    }

    @Override
    public Brand findById(Long id) {
        if (id < 0 ) {
            ApiAssert.failed("这是个错误信息，用来展示给用户看的");
        }
        return this.brandMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Brand> list(PageDto pageDto) {
        PageHelper.startPage(pageDto.getPageNum(),pageDto.getPageSize()); // 接下来执行的一条sql语句，将执行分页查询
        BrandExample example = new BrandExample();
        return brandMapper.selectByExample(example);
    }



    @Override
    public List<Brand> listAllBrand() {
        return brandMapper.selectByExample(new BrandExample());
    }

    @Override
    public int createBrand(Brand brand) {
        return brandMapper.insertSelective(brand);
    }

    @Override
    public int updateBrand(Long id, Brand brand) {
        brand.setId(id);
        return brandMapper.updateByPrimaryKeySelective(brand);
    }

    @Override
    public int deleteBrand(Long id) {
        return brandMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<Brand> listBrand(PageDto page) {
        if (page.getPageNum() < 1 || page.getPageSize() < 1) {
            ApiAssert.failed("无效参数");
        }
        if (page.getPageSize() > 20) {
            page.setPageSize(20); // 每页最多显示20跳
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return brandMapper.selectByExample(new BrandExample());
    }

    @Override
    public Brand getBrand(Long id) {
        return brandMapper.selectByPrimaryKey(id);
    }
}
